package com.jian.dao;

import com.jian.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.jetbrains.annotations.NotNull;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Jiange
 * @create 2021-04-11-22:27
 */
public class BaseBDao {
    private QueryRunner queryRunner = new QueryRunner();

    /**
     * 用于增删改的方法
     * @param sql 语句
     * @param param 占位符的参数
     * @return 改变了的行数
     * @throws SQLException
     */
    public int update(@NotNull String sql, Object...param) throws SQLException {
        int update = queryRunner.update(JDBCUtils.getConnection(), sql, param);
        return update;
    }

    /**
     * 查询封装成一个JavaBean对象
     * @param type
     * @param sql
     * @param param
     * @param <T>
     * @return
     * @throws SQLException
     */
    public <T> T queryForOne(Class<T> type,@NotNull String sql,Object...param) throws SQLException {
        T query = queryRunner.query(JDBCUtils.getConnection(), sql, new BeanHandler<T>(type), param);
        return query;
    }

    /**
     * 查询封装成list类型的javaBean对象
     * @param type
     * @param sql
     * @param param
     * @param <T>
     * @return
     * @throws SQLException
     */
    public <T> List<T> queryForList(Class<T> type,@NotNull String sql,Object...param) throws SQLException {
        List<T> query = queryRunner.query(JDBCUtils.getConnection(), sql, new BeanListHandler<T>(type), param);
        return query;
    }

    /**
     * 查询单列值
     * @param sql
     * @param param
     * @return
     * @throws SQLException
     */
    public Object querySingle(@NotNull String sql,Object...param) throws SQLException {
        Object query = queryRunner.query(JDBCUtils.getConnection(), sql, new ScalarHandler<>(), param);
        return query;
    }
}
